#include "Actor.h"

Actor::Actor()
{
    //初始化坐标
    x = 0;
    y = 0;
    xVel = 0;
    yVel = 0;
    nowFrameIndex = 0.0;
    animPre = 1;
    //初始化速率
    setClips();
    background = nullptr;
}


Actor::~Actor()
{
    if(background != nullptr)
    {
        SDL_DestroyTexture(background);
    }
}


void Actor::show(SDL_Renderer *renderer)
{
    x += xVel;
    y += yVel;
    SDL_Rect dstPos;
    dstPos.x = x;
    dstPos.y = y;
    dstPos.w = ACTOR_WIDTH;
    dstPos.h = ACTOR_HEIGHT;

    nowFrameIndex = (float)SDL_GetTicks()/1000*ACTOR_COUNT*animPre;
    SDL_RenderCopy(renderer, background, &clips[(int)nowFrameIndex%ACTOR_COUNT],  &dstPos);
}

SDL_Texture* Actor::LoadImage(SDL_Renderer *renderer, string file)
{
    SDL_Texture* tex = nullptr;
    tex = IMG_LoadTexture(renderer, file.c_str());
    if (tex == nullptr)
    {
        throw runtime_error("Failed to load image: " + file + IMG_GetError());
    }
    return tex;
}

void Actor::setBackground(SDL_Renderer *renderer, string filename)
{
    if(background != nullptr)
    {
        SDL_DestroyTexture(background);
    }

    this->background = LoadImage( renderer, filename);
}


void Actor::setClips()
{
    //剪切子图
    for ( int i = 0; i < ACTOR_COUNT; i++ )
    {
        clips[ i ].x = ACTOR_WIDTH * i;
        clips[ i ].y = 0;
        clips[ i ].w = ACTOR_WIDTH;
        clips[ i ].h = ACTOR_HEIGHT;
    }
}


void Actor::handleEvent(SDL_Event event)
{
    //当一个键被按下
    if( event.type == SDL_KEYDOWN )
    {
        //调整速度
        if(event.key.keysym.sym == SDLK_UP)
        {
            yVel = -10;
        }
        else if(event.key.keysym.sym == SDLK_DOWN)
        {
            yVel = 10;
        }
        else if(event.key.keysym.sym == SDLK_LEFT)
        {
            xVel = -10;
        }
        else if(event.key.keysym.sym == SDLK_RIGHT)
        {
            xVel = +10;
        }
    }
    //当一个键盘按键被松开
    else if( event.type == SDL_KEYUP )
    {
        //调整速度
        if(event.key.keysym.sym == SDLK_UP)
        {
            yVel = 0;
        }
        else if(event.key.keysym.sym == SDLK_DOWN)
        {
            yVel = 0;
        }
        else if(event.key.keysym.sym == SDLK_LEFT)
        {
            xVel = 0;
        }
        else if(event.key.keysym.sym == SDLK_RIGHT)
        {
            xVel = 0;
        }
    }
}


void Actor::setAnimPre(float animPre)
{
    this->animPre = animPre;
}

float Actor::getAnimPre()
{
    return this->animPre;
}